/* DictOption */
import { defineStore } from 'pinia'
import { handleDefaultSetting, type DictOptionStore, type DictOption } from './helper'
import { fetchQueryDictByNameList } from '@/api'

// Export store
export const useDictOptionStore = defineStore(`dict-option-store`, {
  state: (): DictOptionStore => handleDefaultSetting(),
  getters: {},
  actions: {
    /**
     * 查询字典表
     * @param dictNameList 字典名称列表
     * @return {DictOption} 搜索条件
     */
    async query<T>(dictNameList: Array<string>) {
      const {
        data: { conditions }
      } = await fetchQueryDictByNameList<{ conditions: T }>(dictNameList)
      Object.assign(this.dictOption, conditions)
      return conditions
    },
    /**
     * 将字典代码转换为字典名称
     * @param dictCode 字典代号
     * @param dictID 字典代码
     * @return {string} 字典名称
     */
    convertCodeToDictName(dictCode: string, dictID: number) {
      if (!dictCode || !dictID) return ''
      const _arr = this.dictOption[dictCode]['children'] || []
      for (const item of _arr) {
        if (item.id === dictID) {
          return item.dictName
        }
      }
    },
    /**
     * 判断字符串是否为字典名称
     * @param key 字符串
     * @return {string} 字典名称
     */
    checkIsDictName(key: string) {
      if (!key) return false
      return Object.keys(this.dictOption).includes(key)
    }
  }
})
